'use strict';
const ws = require("nodejs-websocket");
const _ = require('lodash');

let user_count = 0;
const server = ws.createServer(function (conn) {
    let id = ++ user_count;
    let user_name = 'User' + id;
    broadcast(user_name + ' join our chat room.')
    conn.on("text", function (str) {
        console.log(user_name + ':', str);
        broadcast(user_name + ': ' + str);
    });

    function left() {
        broadcast(user_name + ' left our chat room.')
    }
    conn.on("close", function (code, reason) {
        console.log("Connection closed", user_name, code, reason);
        left();
    });
    conn.on('error', function (err) {
        console.log('error', user_name, err);
        left();
    });
}).listen(8001);


function broadcast(message) {
    _.each(server.connections, conn => {
        conn.send(message);
    });
}